<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="company-box box-card">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 新增按钮 -->
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="editRoleDialog = true">新增</el-button>
            <!-- 表格 -->
            <el-table
              border
              :data="role"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="150"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
                sortable
              />
              <el-table-column
                prop="description"
                label="描述"
                sortable
              />
              <el-table-column
                prop="address"
                label="操作"
                width="250"
                align="center"
              >
                <template v-slot="{ row }">
                  <el-button type="text" size="mini" @click="onSetPermission(row)">分配权限</el-button>
                  <el-button type="text" size="mini" @click="editRole(row)">修改</el-button>
                  <el-button type="text" size="mini" @click="onDelRoles(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              :current-page="page.page"
              :page-size="page.pagesize"
              layout="total, prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="info">
            <el-form label-width="200px" style="width: 650px" :model="companyForm" disabled>
              <el-form-item label="企业名称">
                <el-input v-model="companyForm.name" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" />
              </el-form-item>
              <el-form-item label="公司电话">
                <el-input v-model="companyForm.companyPhone" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 修改对话框 -->
    <el-dialog
      :title="(form.id ? '编辑': '新增') + '角色'"
      :visible.sync="editRoleDialog"
      width="30%"
      @close="onDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="setPermissionTitle"
      :visible.sync="setPermissionDialog"
      width="30%"
      @close="onPermissionClose"
    >
      <el-tree
        v-if="setPermissionDialog"
        ref="setPermissionTree"
        node-key="id"
        :check-strictly="true"
        :default-checked-keys="defaultKeys"
        icon-class=" "
        :data="permissionLits"
        :props="defaultProps"
        show-checkbox
        default-expand-all
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="onPermissionClose">取 消</el-button>
        <el-button type="primary" @click="onSetPermissionSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, delRole, getRoleById, updateRole, addRole, getCompany } from '@/api/company.js'
import { getPermissionList, setPermissionToRole } from '@/api/permission.js'
import { transListToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role', // 切换标签页
      role: [], // 角色管理的数据
      companyForm: {
        name: '',
        companyAddress: '',
        companyPhone: '',
        mailbox: '',
        remarks: ''
      }, // 公司管理的数据
      page: {
        page: 1, // 页码
        pagesize: 10 // 每页的条数
      },
      total: 20, // 总条数
      editRoleDialog: false, // 开启关闭修改对话框
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      setPermissionDialog: false, // 分配权限对话框开关
      setPermissionTitle: '', // 分配权限对话框的标题
      permissionLits: [], // 分配权限对话框的数据
      defaultProps: { // 分配权限对话框的数据渲染规则
        children: 'children',
        label: 'name'
      },
      defaultKeys: [], // 分配权限的默认选中
      roleId: '' // 分配权限点击行的角色id
    }
  },

  created() {
    this.loadRoleList()
    this.onCompany()
  },

  methods: {
    // 加载角色列表
    async loadRoleList() {
      const res = await getRoleList(this.page)
      this.role = res.rows
      this.total = res.total
    },

    // 加载公司列表
    async onCompany() {
      const res = await getCompany()
      this.companyForm = res[0]
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.page.page = val
      this.loadRoleList()
    },

    // 点击删除
    onDelRoles(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRole(id)
        this.$message.success('删除成功')
        this.loadRoleList()
      }).catch(() => {})
    },

    // 点击修改
    async editRole(row) {
      const res = await getRoleById(row.id)
      this.form = res
      this.editRoleDialog = true
    },

    // 点击修改对话框的确定
    async onSave() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 更新角色
          await updateRole(this.form)
          this.$message.success('修改成功')
        } else {
          // 新增
          await addRole(this.form)
          this.$message.success('添加成功')
        }
        this.editRoleDialog = false
        this.loadRoleList()
      } catch (error) {
        console.log(error)
      }
    },

    // 关闭修改对话框的回调
    onDialogClose() {
      this.$refs.form.resetFields()
      setTimeout(() => {
        this.form = {
          name: '',
          description: ''
        }
      }, 200)
    },

    // 点击分配权限触发
    async onSetPermission(row) {
      this.roleId = row.id
      this.setPermissionTitle = '为[' + row.name + ']分配权限'
      this.setPermissionDialog = true
      this.permissionLits = transListToTree(await getPermissionList(), '0')
      // 获取已有权限
      this.defaultKeys = (await getRoleById(row.id)).permIds
    },

    // 点击分配权限的确认
    async onSetPermissionSave() {
      const permissionIds = this.$refs.setPermissionTree.getCheckedKeys()
      if (!permissionIds.length) return this.$message.error('请选择必要的权限')
      await setPermissionToRole({
        id: this.roleId,
        permIds: permissionIds
      })
      this.$message.success('分配成功')
      this.onPermissionClose()
    },

    // 关闭分配权限的对话框
    onPermissionClose() {
      this.setPermissionDialog = false
      this.defaultKeys = []
    }
  }
}
</script>

<style scoped lang='scss'>
.company-box {
  ::v-deep.el-tabs__item {
    font-size: 18px;
    padding: 0 40px;
    width: 150px;
    text-align: center;
  }

  .el-pagination{
    display: flex;
    justify-content: flex-end;
  }
}
</style>
